#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

extern char **environ;
static pthread_mutex_t env_mutex=PTHREAD_MUTEX_INITIALIZER;

int putenv_r(char *name) {
    int len;
    int key_len;
    int i;
    int err;
    int setflag= 0;
    char *newp;
    sigset_t fillset, oset;

    len= strlen(name);
    key_len= 0;
    for (i=0; i<len; ++i) {
        if (name[i] == '=') {
            key_len= i;
            break;
        } 
    }
    if (key_len == 0)
        return EINVAL;

    sigfillset(&fillset);
    if ((err= pthread_sigmask(SIG_BLOCK, &fillset, &oset)) != 0) 
        return err;

    pthread_mutex_lock(&env_mutex);

    newp= malloc((len+1) * sizeof(char));
    strcpy(newp, name);



    for (i=0; environ[i] != NULL; ++i) {
        if (strncmp(name, environ[i], key_len) == 0) {
            environ[i]= newp;
            setflag= 1;
        }
    }

    if (!setflag) {
        environ[i]= newp;
        environ[i+1]= NULL;
    }

    pthread_mutex_unlock(&env_mutex);
    pthread_sigmask(SIG_SETMASK, &oset, NULL);
    return 0;
}
